//request.js
import axios from "axios";
import qs from "qs";
import router from "../main.js";

//引用全局变量文件
import GLOBAL_FUN from './global_function.js'
import GLOBAL_VAR from './global_variable.js'

//测试token
//let token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiaXNzIjoicHJvLXNlcnZlciJ9.4-eF585mt-AcixNoeUbX-30Jc6uq8Eiz7tqrQUGrCM8'

// 设置axios跨域访问
axios.defaults.withCredentials = true // 设置cross跨域 并设置访问权限 允许跨域携带cookie信息
axios.defaults.crossDomain = true // 设置axios跨域的配置

/****** 创建axios实例 ******/
const service = axios.create({
    baseURL: GLOBAL_VAR.loginBaseUrl, // api的base_url
    timeout: 30000, // 请求超时时间
    withCredentials: true //启用session,每次请求带sessionid
});

/****** request拦截器==>对请求参数做处理 ******/
service.interceptors.request.use(config => {
    const timestamp = new Date().getTime() + Math.floor(Math.random() * 10)
    config.headers._t = timestamp
    config.Cookie = 'Hm_lvt_5819d05c0869771ff6e6a81cdec5b2e8=1692233608,1692320601,1692351025,1692354564'
    console.log('config', config)
    //config.method === 'get' ? config.params = qs.stringify({ ...config.data}) : config.params = { ...config.params };
    if (config.method === 'get') {
        config.params = {
            ...config.data
        };
    } else {
        const dataStr = JSON.stringify(config.data || config.params)
        let sortStr = ''
        let md5Str = ''
        const data = GLOBAL_FUN.getMd5Str(dataStr, timestamp)
        sortStr = data.sortStr
        md5Str = data.md5Str
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
        config.params = {
            _t: timestamp,
            _sign: md5Str,
            ...config.params
        };
    }
    if (config.loading === false) {} else {
        GLOBAL_FUN.startLoading()
    }
    //json数据格式进行前后端交付
    if (config.url === '/login' || config.url === '/logout') {
        config.data = qs.stringify({
            ...config.data
        })
    } else {
        config.headers['Content-Type'] = GLOBAL_VAR.contentType;
    }

    //添加登录token到header中
    let token = GLOBAL_FUN.getToken();
    if (token && token !== null && token !== 'null') {
        config.headers['Jf-Session-Id'] = token;
    }
    return config;
}, error => { //请求错误处理
    GLOBAL_FUN.endLoading()
    Promise.reject(error)
});


/****** respone拦截器==>对响应做处理 ******/
service.interceptors.response.use(
    response => { //成功请求到数据
        GLOBAL_FUN.endLoading();
        console.log('response');
        console.log(response);
        //这里根据后端提供的数据进行对应的处理
        if (response.data) {
            const resultData = response.data
            let code = resultData.code;
            let msg = resultData.message;
            if (code == '200') {
                return response.data;
            } else if (code == '-1') {
                msg = '您未登录或会话失效'
                logout();
            }
            GLOBAL_FUN.errorMsg(msg);
        } else {
            return response.data;
        }
    },
    error => { //响应错误处理
        console.log('response error', error);
        // let text = JSON.parse(JSON.stringify(error)).response.status === 404 ?'404':'网络异常，请重试';
        GLOBAL_FUN.endLoading();
        let msg = "操作失败";
        if (error) {
            if (error.response) {
                if (error.response.status == 404 || error.response.status == 504) {
                    msg = '网络异常，请稍后重试';
                } else if (error.response.status == 403) {
                    msg = '您无权限访问该资源';
                    console.log('您无权限访问该资源', '-1');
                    logout();
                } else if (error.response.status == 401) {
                    msg = '您未登录或会话失效';
                    console.log('您未登录或会话失效', '-1');
                    logout();
                } else {
                    if (error.response.data) {
                        if (error.response.data.msg) {
                            msg += ": " + error.response.data.msg;
                        }
                        if (error.response.data.code == '-1') {
                            console.log(msg);
                            GLOBAL_FUN.errorMsg(msg);
                        }
                    }
                }
            }
        }
        GLOBAL_FUN.errorMsg(msg);
        return Promise.reject(error)
    }
);
/**
 * 退出登录
 */
function logout() {
    router.push({
        path: '/toLogin',
        query: {}
    });
}
export default service;